package com.vhdadw.service.serciveImpl;

import com.vhdadw.config.RabbitMQConfig;
import com.vhdadw.controller.request.AccountLoginRequest;
import com.vhdadw.controller.request.AccountRegisterRequest;
import com.vhdadw.enums.AuthTypeEnum;
import com.vhdadw.enums.BizCodeEnum;
import com.vhdadw.enums.EventMessageType;
import com.vhdadw.enums.SendCodeEnum;
import com.vhdadw.manager.AccountManager;
import com.vhdadw.mapper.AccountMapper;
import com.vhdadw.model.AccountDO;
import com.vhdadw.model.EventMessage;
import com.vhdadw.model.LoginUser;
import com.vhdadw.service.AccountService;
import com.vhdadw.service.NotifyService;
import com.vhdadw.utils.CommonUtil;
import com.vhdadw.utils.IDUtil;
import com.vhdadw.utils.JWTUtil;
import com.vhdadw.utils.JsonData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private AccountManager accountManager;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RabbitMQConfig rabbitMQConfig;
    /**
     * 免费流量包id固定为1
     */
    private static final Long FREE_TRAFFIC_PRODUCT_ID =1L;

    /**
     * ⼿机验证码验证
     * 密码加密（TODO）
     * 账号唯⼀性检查(TODO)
     * 插⼊数据库
     * 新注册⽤户福利发放(TODO)
     *
     * @param registerRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public JsonData register(AccountRegisterRequest registerRequest) {

        boolean checkCode = false;
        //判断验证码
        if (StringUtils.isNotBlank(registerRequest.getCode())) {
            checkCode = notifyService.checkCode(SendCodeEnum.USER_REGISTER, registerRequest.getPhone(), registerRequest.getCode());
        }
        //验证码错误
        if (!checkCode) {
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }

        AccountDO accountDO = new AccountDO();
        BeanUtils.copyProperties(registerRequest, accountDO);

        //认证级别
        accountDO.setAuth(AuthTypeEnum.DEFAULT.name());

        //生成唯一的账号
        accountDO.setAccountNo(Long.valueOf(IDUtil.generateSnowFlakeID().toString()));

        //设置密码 秘钥
        accountDO.setSecret("$1$" + CommonUtil.getStringNumRandom(8));
        String cryptPwd = Md5Crypt.md5Crypt(registerRequest.getPwd().getBytes(), accountDO.getSecret());
        accountDO.setPwd(cryptPwd);

        int rows = accountManager.insert(accountDO);
        log.info("rows:{},注册成功:{}", rows, accountDO);

        //用户注册成功，发放福利
        userRegisterInitTask(accountDO);

        return JsonData.buildSuccess();
    }

    /**
     * 1.根据手机号查询
     * 2.获取盐
     *
     * @param request
     * @return
     */
    @Override
    public JsonData login(AccountLoginRequest request) {

        List<AccountDO> accountDOList = accountManager.findByPhone(request.getPhone());

        if (accountDOList != null && accountDOList.size() == 1) {

            AccountDO accountDO = accountDOList.get(0);

            //获取盐
            String md5Crypt = Md5Crypt.md5Crypt(request.getPwd().getBytes(), accountDO.getSecret());
            if (md5Crypt.equalsIgnoreCase(accountDO.getPwd())) {

                LoginUser loginUser = LoginUser.builder().build();
                BeanUtils.copyProperties(accountDO, loginUser);
                System.out.println(loginUser);

                String token = JWTUtil.generateJsonWebToken(loginUser);
                return JsonData.buildSuccess(token);

            } else {
                return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
            }
        } else {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
        }
    }

    /**
     * 用户初始化，发放福利，流量包 TODO
     *
     * @param accountDO
     */
    private void userRegisterInitTask(AccountDO accountDO) {

        EventMessage eventMessage = EventMessage.builder()
                .messageId(IDUtil.generateSnowFlakeID().toString())
                .accountNo(accountDO.getAccountNo())
                .eventMessageType(EventMessageType.TRAFFIC_FREE_INIT.name())
                .bizId(FREE_TRAFFIC_PRODUCT_ID.toString())
                .build();

        //发送发放流量包消息
        rabbitTemplate.convertAndSend(rabbitMQConfig.getTrafficExchange(),rabbitMQConfig.getTrafficFreeIniRoutingKey(),eventMessage);

    }
}
